/**
 * 
 */
package com.ydy.service.user.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydy.constant.SystemConstant;
import com.ydy.exception.BusinessException;
import com.ydy.exception.DataNotFoundException;
import com.ydy.exception.ValidateException;
import com.ydy.ienum.EnumUser;
import com.ydy.mapper.UserMapper;
import com.ydy.mapper.WechatUserMapper;
import com.ydy.model.User;
import com.ydy.model.WechatUser;
import com.ydy.remote.wechat.WeChatApi;
import com.ydy.service.user.UserService;
import com.ydy.utils.Md5Util;
import com.ydy.utils.TokenUtil;
import com.ydy.utils.ValidateUtil;
import com.ydy.vo.other.PageVo;
import com.ydy.vo.token.UserTokenVo;

/**
 * @author xuzhaojie
 *
 *         2019年5月29日 上午8:35:26
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
	private final static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WechatUserMapper wechatUserMapper;

	@Override
	public PageVo<User> select(User user, Integer page, Integer size) {
		PageVo<User> vo = new PageVo<User>(page, size);
		Page<User> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "id desc");
		List<User> list = userMapper.select(user);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public UserTokenVo checkUser(User user) {
		User temp = null;
		User record = new User();
		record.setUserName(user.getUserName());
		record.setPassword(Md5Util.getMD5(record.getPassword()));
		List<User> list = userMapper.select(record);
		if (list.size() <= 0) {
			log.info("找不到该user:" + user.getUserName());
			throw new DataNotFoundException(EnumUser.DATA_NOT_FOUND);
		}
		temp = list.get(0);
		if (temp == null || !Objects.equals(Md5Util.getMD5(user.getPassword()), temp.getPassword())) {
			log.info("user登录密码错误:" + user.getUserName());
			throw new BusinessException(EnumUser.PWD_ERROR);
		}
		String token = TokenUtil.createUserToken(temp);
		UserTokenVo vo = new UserTokenVo();
		vo.setUtoken(token);
		vo.setTimestamp(System.currentTimeMillis());
		return vo;
	}

	@Override
	public User saveOrUpdate(User user) {
		if (user == null) {
			throw new NullPointerException();
		}
		// 校验数据有效
		Map<String, String> validateInfo = ValidateUtil.validateEntity(user);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		// 新增user信息
		String username = "USER." + user.getUserName();// 同步，防止同时对一个user进行修改
		synchronized (username.intern()) {
			if (user.getId() == null) {
				User record = new User();
				record.setUserName(user.getUserName());
				List<User> list = userMapper.select(record);
				if (list.size() > 0) {// 用户名已存在
					throw new BusinessException(EnumUser.USERNAME_EXSIT);
				}
				user.setCreateTime(new Date());
				userMapper.insertSelective(user);
				log.info("新增user信息成功:" + user.getUserName());
			} else {// 根据id更新信息
				if (userMapper.selectByPrimaryKey(user.getId()) == null) {// 不存在该id信息
					throw new DataNotFoundException(EnumUser.DATA_NOT_FOUND);
				}
				user.setUserName(null);// 不能修改用户名
				user.setCreateTime(null);// 不能修改注册时间
				userMapper.updateByPrimaryKeySelective(user);
				log.info("修改user信息成功:" + user.getUserName());
				user = userMapper.selectByPrimaryKey(user.getId());
			}
		}
		return user;
	}

	@Override
	public UserTokenVo loginByWechat(String code) {
		if (StringUtils.isEmpty(code)) {
			throw new NullPointerException();
		}
		WechatUser wechatUser = WeChatApi.getUserInfo(WeChatApi.getWebAccessToken(code));
		String openId = wechatUser.getOpenid();
		if (StringUtils.isEmpty(openId)) {
			throw new BusinessException(EnumUser.OPENID_EMPTY);
		}
		WechatUser example = new WechatUser();
		example.setOpenid(openId);
		WechatUser temp = wechatUserMapper.selectOne(example);
		// 新增信息
		User user = null;
		if (temp == null) {
			user = new User();
			user.setCreateTime(new Date());
			user.setHeadUrl(wechatUser.getHeadimgurl());
			user.setNickName(wechatUser.getNickname());
			user.setPassword(Md5Util.getMD5(wechatUser.getOpenid()));
			if (SystemConstant.GENDER_MAN.toString().equals(wechatUser.getSex())) {
				user.setSex(SystemConstant.GENDER_MAN);
			} else {
				user.setSex(SystemConstant.GENDER_MALE);
			}
			user.setUserName(Md5Util.getMD5(wechatUser.getOpenid()));
			userMapper.insertSelective(user);
			wechatUser.setUserId(user.getId());
			wechatUserMapper.insertSelective(wechatUser);
			log.info("新增user成功：" + user.getId());
		} else {// 根据id更新信息
			user = userMapper.selectByPrimaryKey(temp.getUserId());
			if (user == null) {
				log.info("找不到user信息：" + temp.getUserId());
				throw new DataNotFoundException(EnumUser.DATA_NOT_FOUND);
			}
			wechatUser.setUserId(temp.getUserId());
			wechatUserMapper.updateByPrimaryKeySelective(wechatUser);
			log.info("更新user成功：" + user.getId());
		}
		user.setOpenId(wechatUser.getOpenid());
		String token = TokenUtil.createUserToken(user);
		UserTokenVo vo = new UserTokenVo();
		vo.setUtoken(token);
		vo.setTimestamp(System.currentTimeMillis());
		return vo;
	}

	@Override
	public User selectById(Long id) {
		if (id == null) {
			throw new NullPointerException();
		}
		User temp = userMapper.selectByPrimaryKey(id);
		if (temp == null) {
			throw new BusinessException(EnumUser.DATA_NOT_FOUND);
		}
		return temp;
	}

}
